import json

from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import render

from crawler.business.models import House
from crawler.common.db import DBUtils
from crawler.common.http import HttpUtils


def businesses(request):
    return render(request, 'business/business.html')


def lianjia(request):
    houses = __houses(request)
    return render(request, 'business/lianjia.html', {"houses": houses})


def houses_json(request):
    houses = __houses(request)
    houses_json = json.dumps(houses, ensure_ascii=False)
    return HttpResponse(houses_json, content_type="application/json")


def lianjia_crawl(request):
    url = settings.CRAWLER_BASE_URL
    url += "crawler/crawl"
    data = HttpUtils.get(url)

    return HttpResponse(json.dumps(data), content_type="application/json")

def map(request):
    return render(request, 'business/house_map.html')


def __houses(request):
    db = DBUtils()
    page = request.GET.get('page')
    page = int(page) if page is not None else 10
    houses = {}
    sql = "select count(ID) as count from lj_house limit 0,10"
    dataset = db.fetchone(sql)
    count = dataset["count"]
    page_size = 10
    cur_page = page
    total_page = count / page_size + 1
    prev_page = page - 1 if page > 1 else page
    next_page = page + 1 if page < total_page else page
    houses["pager"] = {}
    houses["pager"]["cur_page"] = cur_page
    houses["pager"]["prev_page"] = prev_page
    houses["pager"]["next_page"] = next_page

    houses["data"] = []
    sql = "select ID as id,C_TITLE as name, C_LOCATION as address, C_FLOORSPACE as area, C_PRICE as amount, C_UNIT_PRICE as price from lj_house order by convert(C_LOCATION using utf8) asc limit " + str(
        (page - 1) * 10) + ",10"
    dataset = db.fetchall(sql)
    for data in dataset:
        house = House()
        house.id = data["id"]
        house.name = data["name"]
        house.address = data["address"]
        house.area = data["area"]
        house.amount = data["amount"]
        house.price = data["price"]
        if house is not None:
            house_dict = {}
            house_dict.update(house.__dict__)
            house_dict.pop("_state", None)
            houses["data"].append(house_dict)
    return houses
